<?php

namespace Biz\model\brandActivity;

use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;

class BlindBoxActivity extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_brand_activity';

    const _DATABASE_ = 'brand_activity';

    const _TABLE_NAME = 'blind_box_activity';

    const ACTIVITY_TYPE_BLIND_BOX = 1;//活动类型，超级盲盒

    const ACTIVITY_STATE_DRAFT = 0;//草稿状态
    const ACTIVITY_STATE_NORMAL = 1;//待审核
    const ACTIVITY_STATE_PASS = 2;//审核通过（待上线）
    const ACTIVITY_STATE_UN_PASS = 3;//审核不通过
    const ACTIVITY_STATE_ONLINE = 4;//已上线 虚拟根据时间展示
    const ACTIVITY_STATE_END = 5;//已结束 虚拟根据时间展示
    const ACTIVITY_STATE_DEL = 9;//已删除

    const PRIZE_TYPE_GOODS = 1;//实物奖品
    const PRIZE_TYPE_SHOP_COUPON = 2;//全店通用券
    const PRIZE_TYPE_GOOD_COUPON = 3;//单品优惠券
    const PRIZE_TYPE_JD_CARD = 4;//京东卡
    const PRIZE_TYPE_LIMIT_CARD = 5;//限定卡
    const PRIZE_TYPE_POINT = 11;//积分
    const PRIZE_TYPE_CUE_CARD = 12;//提示卡
    const PRIZE_TYPE_EMPTY_BOX = 0;//空盒子

    public static $activityStateDesc = [
        self::ACTIVITY_STATE_DRAFT => '草稿箱',
        self::ACTIVITY_STATE_NORMAL => '待审核',
        self::ACTIVITY_STATE_PASS => '待上线',
        self::ACTIVITY_STATE_UN_PASS => '审核不通过',
        self::ACTIVITY_STATE_ONLINE => '活动进行中',
        self::ACTIVITY_STATE_END => '活动已结束',
        self::ACTIVITY_STATE_DEL => '活动已取消'
    ];
    public static $resereveActivityStateDesc = [
        self::ACTIVITY_STATE_PASS => '待上线',
        self::ACTIVITY_STATE_ONLINE => '活动进行中',
        self::ACTIVITY_STATE_END => '活动已结束',
        self::ACTIVITY_STATE_DEL => '活动已取消'
    ];

    public static $prizeTypeDesc = [
        self::PRIZE_TYPE_GOODS => '实物奖品',
        self::PRIZE_TYPE_SHOP_COUPON => '全店通用券',
        self::PRIZE_TYPE_GOOD_COUPON => '单品优惠券',
        self::PRIZE_TYPE_JD_CARD => '京东卡',
        self::PRIZE_TYPE_LIMIT_CARD => '限定卡'
    ];

    public static function getInfoById($id, $format = true)
    {
        $info = self::getByWhere(['id' => $id]);
        if ($format) {
            $info = self::formatInfo($info);
        }
        return $info;
    }

    public static function getInfoByIdOfMaster($id)
    {
        $info = self::select_master("*", ['id' => $id]);
        if ($info) {
            $info = array_shift($info);
        }
        return $info;
    }

    public static function getBlindBoxList($where)
    {
        $list = self::selectByWhere($where);
        $result = [];
        foreach ($list as $row) {
            $info = self::formatInfo($row);
            $result[$row['id']] = $info;
        }
        return $result;
    }

    public static function getBlindBoxCount($where)
    {
        return self::selectCountWhere($where);
    }

    public static function getByWhere($where, $select = '*')
    {
        return self::get($select, $where);
    }

    public static function selectByWhere($where, $select = '*')
    {
        $list = self::select($select, $where);
        return $list;
    }

    public static function selectCountWhere($where)
    {
        $count = self::count('id', $where);
        return $count;
    }


    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();
    }


    public static function updateData($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function formatInfo($info)
    {
        $now = time();
        if ($info['activity_state'] == self::ACTIVITY_STATE_PASS && $info['start_time'] && $info['end_time']) {
            if ($now >= $info['start_time'] && $now <= $info['end_time']) {
                $info['activity_state'] = self::ACTIVITY_STATE_ONLINE;
            }
            if ($now > $info['end_time']) {
                $info['activity_state'] = self::ACTIVITY_STATE_END;
            }
        }
        return $info;
    }

    /**
     * 减奖品库存
     * @param $id
     * @return bool
     */
    public static function decrPrizeStock($id)
    {
        $info = self::select_master("*", Medoo::raw(' where id=:id for update', [':id' => $id]));
        if ($info) {
            $info = array_shift($info);
            if ($info['prize_stock']) {
                $stock = $info['prize_stock'] - 1;
                if ($stock < 0) {
                    throw new \Exception('减库存失败，库存超减#stock:' . $stock);
                }
                return self::updateData(['prize_stock' => $stock], ['id' => $id]);
            } else {
                throw new \Exception('减库存失败，当前库存:' . $info['prize_stock'] . '#活动信息：' . json_encode($info, JSON_UNESCAPED_UNICODE));
            }
        } else {
            throw new \Exception('查询活动失败#id:' . $id);
        }
    }

}